package com.woniuxy.ShiroIniTest;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Author：向天浩
 * @Date：2022/2/22 20:06
 * @Description :这是我们自定义的域，他需要继承AuthorizingRealm这个类
 */

public class MyRealm extends AuthorizingRealm {
    //这个是授权zation
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //获取用户名强制转换成string
        String primaryPrincipal =(String) principals.getPrimaryPrincipal();

        //创建这个simpleAuthorizationInfo
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();

        //添加角色
        simpleAuthorizationInfo.addRole("role1");
        simpleAuthorizationInfo.addRole("role2");
        simpleAuthorizationInfo.addRole("role3");

        //添加权限
        simpleAuthorizationInfo.addStringPermission("user.update");

        return simpleAuthorizationInfo;
    }

    //这个是认证cation
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //将token这个强制转换成usernamePasswordToken这个类型，就可以获取到用户和密码
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        //密码底层使用了数组来存，我们强制转成字符串
        String password = new String(usernamePasswordToken.getPassword());

       System.out.println(username+password);
        if (password.equals("123456")) {
            //返回的是SimpleAuthenticationInfo；他有三个参数，用户名(username)，认证信息(password)，和指定的域(MyRealm)
            SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo( username,password,"MyRealm");
            return authInfo;
        }else {
            throw new AuthenticationException("用户名或密码错误");
        }

    }
}
